<template>
  <div>
    <!-- 父组件给子组件传值-通过属性的形式 -->
    <home-header></home-header>
    <home-swiper :list="swiperList"></home-swiper>
    <home-icons :list="iconList"></home-icons>
    <home-recommend :list="recommendList"></home-recommend>
    <home-weekend :list="weekendList"></home-weekend>
  </div>
</template>

<script>
// 引入了局部组件之后，需要在下面声明
import HomeHeader from './components/Header'
import HomeSwiper from './components/Swiper'
import HomeIcons from './components/Icons'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import axios from 'axios'
import { mapState } from 'vuex'
export default {
  name: 'Home',
  // 声明局部组件,键和值相同，可省略部分，原本应该是 HomeHeader: HomeHeader
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  // 3. 存所有数据，父组件给子组件传值
  data () {
    return {
      lastCity: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },
  computed: {
    ...mapState(['city'])
  },
  // 2. 函数定义在 methods 里
  methods: {
    getHomeInfo () {
      // 发一个 ajax 请求
      axios.get('/api/index.json?city=' + this.city)
        // 返回值
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      // 当 ajax 获取数据以后，要拿到数据的内容
      res = res.data
      // 如果后端正确返回了结果 并且 res.data 有数据
      if (res.ret && res.data) {
        const data = res.data
        // 以下，获取到数据后，传值给 3，再由3传给子组件
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  // 1. 发送 ajax 请求
  mounted () {
    this.lastCity = this.city
    this.getHomeInfo()
  },
  activated () {
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  }
}
</script>

<style>
</style>
